package utils

import (
	"encoding/json"
	"errors"
	"fmt"
	"math/rand"
	"server/base"
	"time"
)

type UserAuthToken struct {
	RoleId   int64
	RoleType string // service user manage
	RandStr  string
	Time     time.Time
	Key      string
}

func DecodeToken(token string, userInfo interface{}) error {
	if token == "" || token == "null" {
		return errors.New("token is null")
	}

	res, err := Encryption{}.AesDecryptCBC(base.App.Config.AppKey, token)
	if err != nil {
		return errors.New("token decode err")
	}

	err = json.Unmarshal(res, &userInfo)
	if err != nil {
		return errors.New("json decode err")
	}
	return nil
}

func EncodeToken(roleId int64, roleType string) string {
	randStr := fmt.Sprintf("%s_ID-%d-time%s,rand-%d", roleType, roleId, time.Now(), rand.Intn(10000))
	userToken := UserAuthToken{
		RoleId: roleId, RoleType: roleType, RandStr: randStr, Time: time.Now(), Key: base.App.Config.AppKey}
	token, err := json.Marshal(userToken)
	if err != nil {
		return ""
	}
	return Encryption{}.AesEncryptCBC(base.App.Config.AppKey, token)
}
